# from django.shortcuts import render

from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
import json
import requests
import time
from bs4 import BeautifulSoup
import time
import re
import urllib

proxies = {
            "http": "http://qf:qf3.1415@202.112.118.7:10086/"
        }

#返回结果格式
def resultData():
    data = {
        "websiteType" : 0,
        "titleName":"",
        "titleHref": "",
        "source":"",
        "label":"",
        "volume":"",
        "summary":"",
        "detailId":'',
        "publishTime" :"",
        "category" : "",
        "quote" :"",
        "abstract": "",
        "doi": "",
        "downLoad": "",
        "keyword": [],
        "author": [],

    }
    return data

def formData(response):
    allData = []
    # 获取sid并且更新返回
    soup = BeautifulSoup(response.text, "html5lib")
    # print(soup)
    # exit()

    lis = soup.select(".journal")

    for li in lis:
        tempData = resultData()
        try:
            tempData["titleName"] = li.select("dt > a")[0].text.strip()
        except:
            pass
        try:
            tempData["titleHref"] = "http://qw.duxiu.com" + li.select("dt > a")[0]["href"]
        except:
            pass
        try:
            tempData["abstract"] = li.select("dd > p")[0].text.strip()
        except:
            pass
        allData.append(tempData)

    return allData

def getData(keyword):

    headers = {
        'Proxy-Connection': 'keep-alive',
        'Proxy-Authorization': 'Basic cWY6cWYzLjE0MTU=',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Referer': 'http://www.duxiu.com/goqw.jsp?channel=goqw.jsp&ecode=utf-8&sw=%E5%8A%B3%E5%8A%A8&Field=all',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    }

    params = (
        ('sw', keyword),
        ('ecode', 'utf-8'),
    )

    response = requests.get('http://qw.duxiu.com/getPage', headers=headers, params=params, proxies=proxies)



    allData = formData(response)

    return allData

def index(request):
    data = json.loads(request.POST.get('data', '1'))

    allData = getData(data["values"][0])

    return HttpResponse(json.dumps({
        "collection": allData,
        "allNum": 0
    }), content_type="application/json")